import AV from 'leancloud-storage';

AV.init({
  appId: 'xtyEdP2XmT5gq5TGEGSqQPhz-gzGzoHsz',
  appKey: '0z0qekfmtrbUpl0y4NERTRDM',
  serverURL: 'https://xtyedp2x.lc-cn-n1-shared.com'
});

export const roleService = {
  save(roleTemp) {
    // 声明 class
    const Role = AV.Object.extend('role');
    // 构建对象
    const role = new Role();
    // 为属性赋值
    for (const key in roleTemp) {
      role.set(key, roleTemp[key]);
    }
    // 将对象保存到云端
    return role.save();
  },
  query() {
    // 构建查询对象
    const query = new AV.Query('role');
    return query.find();
  },
  remove(id) {
    const todo = AV.Object.createWithoutData('role', id);
    return todo.destroy();
  },
  update(roleTemp) {
    const todo = AV.Object.createWithoutData('role', roleTemp.id);
    delete roleTemp.id;
    // 为属性赋值
    for (const key in roleTemp) {
      todo.set(key, roleTemp[key]);
    }
    return todo.save();
  }
};

export const userService = {
  save(temp) {
    // 声明 class
    const TypeClass = AV.Object.extend('user');
    // 构建对象
    const ins = new TypeClass();
    ins.set('role', AV.Object.createWithoutData('role', temp.roleId[0]));
    delete temp.roleId;
    // 为属性赋值
    for (const key in temp) {
      ins.set(key, temp[key]);
    }
    // 将对象保存到云端
    return ins.save();
  },
  query(roleIds = []) {
    const query = new AV.Query('user');
    if(roleIds.length>0){
      query.containedIn("role", roleIds.map(it=>(AV.Object.createWithoutData('role', it))));
    }
    query.include('role');     // 同时包含博客文章
    return query.find();
  },
  remove(id) {
    const todo = AV.Object.createWithoutData('user', id);
    return todo.destroy();
  },
  update(temp) {
    const todo = AV.Object.createWithoutData('user', temp.id);
    delete temp.id;
    todo.set('role', AV.Object.createWithoutData('role', temp.roleId[0]));
    delete temp.roleId;

    // 为属性赋值
    for (const key in temp) {
      todo.set(key, temp[key]);
    }
    return todo.save();
  }
};


export const banService = {
  update(roleTemp) {
    const todo = AV.Object.createWithoutData('ban', '649bfdd9966d5d052cf08f2e');
    delete roleTemp.id;
    // 为属性赋值
    for (const key in roleTemp) {
      todo.set(key, roleTemp[key]);
    }
    return todo.save();
  },
  async query(roleIds = []) {
    const query = new AV.Query('ban');
    const res = await query.find();
    return res[0];
  },
}

export default AV;
